package maa.servlet;

import maa.action.factory.ActionFactory;
import maa.action.Action;
import maa.action.ActionResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "Controller", urlPatterns = "/do/*")
public class Controller extends HttpServlet {

    ActionFactory actionFactory = new ActionFactory();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String actionName = getActionName(req);
        Action action = actionFactory.getAction(actionName);
        System.out.println("action is " + action);
        try {
            ActionResult actionResult = action.execute(req, resp);
            retrieve(req, resp, actionResult);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void retrieve(HttpServletRequest req, HttpServletResponse resp, ActionResult actionResult) {
        if (actionResult.isRedirected()) redirectTo(req, resp, actionResult.getResult());
        else forwardTo(req, resp, actionResult.getResult());
    }

    private void redirectTo(HttpServletRequest req, HttpServletResponse resp, String result) {
        System.out.println("-");
        String path = req.getServletContext().getContextPath() + "/do?action=" + result;
        try {
            resp.sendRedirect(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void forwardTo(HttpServletRequest req, HttpServletResponse resp, String result) {
        System.out.println("+");
        String path = "/WEB-INF/jsp/" + result + ".jsp";
        try {
            getServletContext().getRequestDispatcher(path).forward(req, resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String getActionName(HttpServletRequest request) {
        String action = request.getMethod() + "/" + request.getParameter("action");
        System.out.println("actionname: " + action);    // LOG!!!
        if (action == null || action.isEmpty()) {
            return "index";
        }
        return action;
    }
}
